package com.xyz.jucTest;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 资源类
 */
class Ticket{
  private int number = 100;
  /**
   * 创建一个锁
   */
  private final Lock lock=new ReentrantLock();

  public  void saleTicket(){
      //加锁
      lock.lock();
      try {
          if(number >0){
              System.out.println(Thread.currentThread().getName()+"\t卖出第:"+(number--)+"张票,剩下:"+number+"张");
          }
      }catch (Exception e){
          e.printStackTrace();
      }finally {
          //关闭锁
          lock.unlock();
      }
  }
}

/**
 * @author 肖咉卓
 *  题目： 三个售票员卖出30张票
 *  多线程编程的企业级套路+模板
 *
 *  1 在高内聚低耦合的前提下，线程 操作(对外暴露的调用方法) 资源类
 */
public class SaleTicket {

    public static void main(String[] args) {
        Ticket ticket=new Ticket();

        new Thread(() ->{for (int i=0;i < 110;i++) {ticket.saleTicket();}},"A").start();
        new Thread(() ->{for (int i=0;i < 110;i++) {ticket.saleTicket();}},"B").start();
        new Thread(() ->{for (int i=0;i < 110;i++) {ticket.saleTicket();}},"C").start();





        /**
         * new Thread 要用串两个参数的
         * 三个线程同时买票
         */
        /*new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i < 110;i++){
                    ticket.saleTicket();
                }
            }
        },"A").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i < 110;i++){
                    ticket.saleTicket();
                }
            }
            },"B").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i < 110;i++){
                    ticket.saleTicket();
                }
            }
            },"C").start();*/
    }

}
